/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.mam.rbac.application.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;

import com.foreveross.bsl.common.utils.bean.BeanHelper;
import com.foreveross.bsl.common.utils.enums.AccountStatus;
import com.foreveross.bsl.common.utils.web.QuerySpecs;
import com.foreveross.bsl.mam.model.rbac.domain.User;
import com.foreveross.bsl.mam.rbac.application.PrivilegeApplication;
import com.foreveross.bsl.mam.rbac.application.RbacUserRoleApplication;
import com.foreveross.bsl.mam.rbac.application.UserApplication;
import com.foreveross.bsl.mam.rbac.application.vo.RoleVO;
import com.foreveross.bsl.mam.rbac.application.vo.UserVO;

/**
 * @description
 * 
 * @author rening
 * @version v1.0
 * 
 * @2013-6-7
 * 
 */
@Named("userApplication")
public class UserApplicationImpl implements UserApplication {

	@Inject
	private RbacUserRoleApplication rbacApplication;


	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.foreveross.bsl.system.application.DatabaseInfoApplication#saveEntity
	 * (com.foreveross.bsl.system.application.vo.DatabaseInfoVO)
	 */

	@Override
	public UserVO saveEntity(UserVO entity) {
		// add by lizhifeng
		entity.setCreateAt(new Date());// user 创建时间
		User user = new User();
		BeanHelper.copyProperties(user, entity);

		Md5PasswordEncoder md = new Md5PasswordEncoder();
		String encodePassword = md.encodePassword(user.getPassword(),
				user.getUsername());
		user.setPassword(encodePassword);
		user.setStatus(AccountStatus.Normal.getValue());
		user.save();
		entity.setId(user.getId());
		return entity;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.foreveross.bsl.system.application.DatabaseInfoApplication#deleteEntity
	 * (com.foreveross.bsl.system.application.vo.DatabaseInfoVO)
	 */
	@Override
	public void deleteEntity(String id) {

		User user = new User();
		user = (User) user.findOne(id);
		user.delete();
		rbacApplication.deleteByUserId(user.getId());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.foreveross.bsl.system.application.DatabaseInfoApplication#getEntity
	 * (java.lang.String)
	 */
	@Override
	public UserVO getEntity(String id) {
		User user = new User();
		user = (User) user.findOne(id);
		UserVO vo = new UserVO();
		BeanHelper.copyProperties(vo, user);
		return vo;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.foreveross.bsl.system.application.DatabaseInfoApplication#findAll()
	 */
	@Override
	public List<UserVO> findAll() {
		User user = new User();
		Iterable iterable = user.findAll();
		if (iterable != null) {
			List<UserVO> result = new ArrayList<UserVO>();
			UserVO vo;
			for (Iterator iterator = iterable.iterator(); iterator.hasNext();) {
				User obj = (User) iterator.next();
				vo = new UserVO();
				BeanHelper.copyProperties(vo, obj);
				if (obj.getStatus().equals(AccountStatus.Disabled.getValue())) {
					vo.setLockOperation("激活");
					vo.setLockStatus("锁定");
				} else {
					vo.setLockOperation("锁定");
					vo.setLockStatus("活动");
				}
				result.add(vo);
			}
			return result;
		}
		return null;
	}

	@Override
	public Page<UserVO> findByPageable(Pageable pageable) {
		User databaseInfo = new User();
		Page page = databaseInfo.findAll(pageable);
		if (page != null && page.getContent() != null) {
			List<UserVO> result = new ArrayList<UserVO>();
			UserVO vo;
			for (Iterator iterator = page.getContent().iterator(); iterator
					.hasNext();) {
				User obj = (User) iterator.next();
				vo = new UserVO();
				BeanHelper.copyProperties(vo, obj);
				if (obj.getStatus().equals(AccountStatus.Disabled.getValue())) {
					vo.setLockOperation("激活");
					vo.setLockStatus("锁定");
				} else {
					vo.setLockOperation("锁定");
					vo.setLockStatus("激活");
				}
				result.add(vo);
				try {
					List<RoleVO> roles = rbacApplication.getRolesByUserID(obj
							.getId());
					if (roles != null) {
						vo.setRoles(roles);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Page<UserVO> pageVO = new PageImpl<UserVO>(result, pageable,
					page.getTotalElements());
			return pageVO;
		}
		return null;
	}

	@Override
	public UserVO updateEntity(UserVO entity) {
		User databaseInfo = new User();
		// entity.setToken(databaseInfo.getToken());
		BeanHelper.copyProperties(databaseInfo, entity);
		databaseInfo.save();
		BeanHelper.copyProperties(entity, databaseInfo);
		return entity;
	}

	@Override
	public UserVO getUserByUserName(String username) {
		User user = new User();
		Query query = Query.query(Criteria.where("username").is(username));
		List<User> us = user.findListByQuery(query);
		if (us == null)
			return null;
		if (us.size() == 0)
			return null;
		user = us.get(0);
		UserVO userVO = new UserVO();
		BeanHelper.copyProperties(userVO, user);
		return userVO;
	}

	@Override
	public Page<UserVO> findUsersBySpec(int pageNumber, int pageSize,
			QuerySpecs querySpecs) {
		Pageable pageable = new PageRequest(pageNumber - 1, pageSize);
		if (querySpecs == null) {
			querySpecs = new QuerySpecs();
		}
		Page<User> page = new User().findByQuerySpecs(querySpecs, pageable);
		return convertToUserVO(page, pageable);
	}

	private Page<UserVO> convertToUserVO(Page<User> page, Pageable pageable) {
		if (page != null && page.getContent() != null) {
			List<UserVO> result = new ArrayList<UserVO>();
			UserVO vo;
			for (Iterator iterator = page.getContent().iterator(); iterator
					.hasNext();) {
				User obj = (User) iterator.next();
				vo = new UserVO();
				BeanHelper.copyProperties(vo, obj);
				if (obj.getStatus().equals(AccountStatus.Disabled.getValue())) {
					vo.setLockOperation("激活");
					vo.setLockStatus("锁定");
				} else {
					vo.setLockOperation("锁定");
					vo.setLockStatus("激活");
				}
				result.add(vo);
				try {
					List<RoleVO> roles = rbacApplication.getRolesByUserID(obj
							.getId());
					if (roles != null) {
						vo.setRoles(roles);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Page<UserVO> pageVO = new PageImpl<UserVO>(result, pageable,
					page.getTotalElements());
			return pageVO;
		} else {
			return null;
		}
	}
}
